<script setup lang="ts">
// 引入vue相关
import { nextTick, onMounted, reactive, ref, Ref } from 'vue'
// 引入element-plus组件
import { ElMessage, FormInstance } from 'element-plus'
// 引入自定义弹框组件
import SysDialog from '@/components/dialog/SysDialog.vue'
// 引入弹框组件的Hooks封装属性和方法
import useDialog from '@/hooks/useDialog.ts'
// 弹框属性和方法
const { dialog, onShow, onClose, onConfirm } = useDialog()
// 获取全局实例
import useInstance from '@/hooks/useInstance.ts'
// 获取全局 global
const { global } = useInstance()

// 引入相关API
import {
  addApi,
  editApi,
  getListApi,
  deleteApi,
} from '@/api/sysDictData'
import {
  SysDictData,
  SysDictDataListParam,
} from '@/api/sysDictData/type'
// 引入相关API
import { getOptionSelect } from '@/api/sysDictType'
import { SysDictType } from '@/api/sysDictType/type'
import { RefreshLeft, Search } from '@element-plus/icons-vue'

// 引入vue-router
import { useRoute } from 'vue-router'
// 获取路由实例
const route = useRoute()

// 定义表单ref实例
const form = ref<FormInstance>()

// 定义表单数据 用于新增和编辑
const formData = reactive<SysDictData>({
  dictCode: undefined, // 字典编码
  dictLabel: '', // 字段标签
  dictValue: '', // 字段值
  dictType: '', // 字典所属类型
  listClass: '', // 表格回显样式
  dictSort: 1, // 字典排序
  remark: '', // 备注
  status: 0, // 状态
})

//定义表单校验规则
const rules = {
  dictLabel: [
    { required: true, message: '请输入字典标签', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
  ],
  dictValue: [
    { required: true, message: '请输入字典键值', trigger: 'blur' },
  ],
  dictType: [{ required: true, message: '请选择字典类型', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// 字典类型下拉列表
const dictTypeOptions = ref<SysDictType[]>([])

// 表格数据和总条数和表格高度和加载效果
const dataList = ref<any[]>([]) // 表格列表数据
const total = ref(0) // 分页器总条数
const loading = ref(false) // 表格加载效果
const tableHeight = ref(0) // 表格内容高度

// 定义搜索表单数据
const searchForm = ref<SysDictDataListParam>({
  dictName: '', // 字典名称
  dictType: '', // 字段类型
  status: undefined, // 状态(0正常 1停用)
  page: 1,
  limit: 10,
})

// 添加一个标志变量，用于标记是否是首次加载
const isFirstLoad = ref(true)

// 获取数据列表方法
const getDictDataList = async () => {
  loading.value = true
  try {
    // 如果是首次加载且路由有参数，则设置查询条件
    if (isFirstLoad.value && route.params.type) {
      searchForm.value.dictType = route.params.type as string
      isFirstLoad.value = false
    }
    const res = await getListApi(searchForm.value)
    dataList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取字典数据列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取字典类型下拉选项
const getDictTypeOptions = async () => {
  try {
    const res = await getOptionSelect()
    dictTypeOptions.value = res.data
  } catch (error) {
    console.error('获取字典类型下拉列表失败:', error)
  }
}

// 搜索方法
const handleSearch = () => {
  searchForm.value.page = 1
  getDictDataList()
}

// 搜索重置方法
const handleReset = () => {
  searchForm.value = {
    dictName: '',
    dictType: '',
    status: undefined,
    page: 1,
    limit: 10,
  }
  getDictDataList()
}

// 提交处理新增或编辑字典数据
const handleSubmit = async () => {
  if (!form.value) return
  await form.value.validate(async (valid) => {
    if (valid) {
      try {
        if (formData.dictCode) {
          await editApi(formData)
          ElMessage.success('编辑字典数据成功')
        } else {
          await addApi(formData)
          ElMessage.success('添加字典数据成功')
        }
        onClose()
        getDictDataList()
      } catch (error) {
        console.error('操作失败:', error)
      }
    }
  })
}

// 编辑数据打开弹出框，并赋值和清理校验
const handleEdit = (row: SysDictData) => {
  dialog.title = '编辑字典数据'
  dialog.width = 600
  dialog.height = 450

  // 重置表单校验
  if (form.value) {
    form.value.resetFields()
  }

  // 使用Object.assign复制数据，避免直接引用导致的问题
  Object.assign(formData, row)

  onShow()
}

// 新增数据，打开弹出框，清理空数据和校验
const handleAdd = () => {
  dialog.title = '新增字典数据'
  dialog.width = 600
  dialog.height = 450

  // 重置表单校验
  if (form.value) {
    form.value.resetFields()
  }

  // 清空表单数据
  Object.assign(formData, {
    dictCode: undefined,
    dictLabel: '',
    dictValue: '',
    dictType: searchForm.value.dictType || '',
    listClass: '',
    dictSort: 1,
    remark: '',
    status: 0,
  })

  onShow()
}

// 删除数据方法
const handleDelete = async (row: SysDictData) => {
  if (!row.dictCode) return

  try {
    await global.$confirm('确定要删除该字典数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await deleteApi(row.dictCode)
    ElMessage.success('删除成功')
    getDictDataList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 分页改变
const handleCurrentChange = (page: number) => {
  searchForm.value.page = page
  getDictDataList()
}

// 每页条数改变
const handleSizeChange = (size: number) => {
  searchForm.value.limit = size
  searchForm.value.page = 1
  getDictDataList()
}

// 页面加载时获取列表数据
onMounted(() => {
  // 获取字典类型下拉选项
  getDictTypeOptions()

  // 获取字典数据列表
  getDictDataList()

  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 310
  })
})
</script>

<template>
  <div class="container">
    <!-- 搜索区域 -->
    <el-card class="search-card"
             shadow="never">
      <div class="search-wrapper">
        <el-form :inline="true"
                 :model="searchForm"
                 class="demo-form-inline">
          <el-form-item label="字典标签">
            <el-input v-model="searchForm.dictName"
                      type="text"
                      placeholder="请输入字典标签"
                      clearable />
          </el-form-item>
          <el-form-item label="字典类型">
            <el-select v-model="searchForm.dictType"
                       placeholder="请选择字典类型"
                       clearable>
              <el-option v-for="item in dictTypeOptions"
                         :key="item.dictType"
                         :label="item.dictName"
                         :value="item.dictType" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status"
                       placeholder="请选择状态"
                       clearable>
              <el-option :value="0"
                         label="正常" />
              <el-option :value="1"
                         label="停用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       :icon="Search"
                       @click="handleSearch">
              查询
            </el-button>
            <el-button :icon="RefreshLeft"
                       @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="list-card"
             shadow="never">
      <div class="tool-bar"
           style="margin-bottom: 15px;">
        <el-button type="primary"
                   @click="handleAdd">新增</el-button>
      </div>
      <el-table :data="dataList"
                :height="tableHeight"
                v-loading="loading"
                element-loading-text="加载中..."
                element-loading-background="rgba(255, 255, 255, 0.7)"
                style="width: 100%"
                stripe
                border>
        <el-table-column type="index"
                         label="序号"
                         width="60"
                         align="center" />
        <el-table-column prop="dictLabel"
                         label="字典标签"
                         show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="scope.row.listClass">
              {{ scope.row.dictLabel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dictValue"
                         label="字典键值"
                         show-overflow-tooltip />
        <el-table-column prop="dictType"
                         label="字典类型"
                         show-overflow-tooltip />
        <el-table-column prop="dictSort"
                         label="排序"
                         show-overflow-tooltip />
        <el-table-column prop="status"
                         label="状态"
                         align="center"
                         width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
              {{ scope.row.status === 0 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark"
                         label="备注"
                         show-overflow-tooltip />
        <el-table-column prop="createTime"
                         label="创建时间"
                         show-overflow-tooltip />
        <el-table-column label="操作"
                         width="200"
                         align="center">
          <template #default="scope">
            <el-button type="primary"
                       link
                       icon="edit"
                       @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary"
                       link
                       icon="Delete"
                       @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页器-->
      <div class="pagination">
        <el-pagination v-model:current-page="searchForm.page"
                       v-model:page-size="searchForm.limit"
                       :page-sizes="[5, 10, 20, 25]"
                       :background="true"
                       layout="prev, pager, next, jumper,->,sizes,total"
                       :total="total"
                       @current-change="handleCurrentChange"
                       @size-change="handleSizeChange" />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <sys-dialog :title="dialog.title"
                :width="dialog.width"
                :visible="dialog.visible"
                :height="dialog.height"
                @onClose="onClose"
                @onConfirm="handleSubmit">
      <template #content>
        <el-form ref="form"
                 :model="formData"
                 :rules="rules"
                 label-width="100px">
          <el-form-item label="字典类型"
                        prop="dictType">
            <el-select v-model="formData.dictType"
                       placeholder="请选择字典类型"
                       style="width: 100%">
              <el-option v-for="item in dictTypeOptions"
                         :key="item.dictType"
                         :label="item.dictName"
                         :value="item.dictType" />
            </el-select>
          </el-form-item>
          <el-form-item label="字典标签"
                        prop="dictLabel">
            <el-input v-model="formData.dictLabel"
                      placeholder="请输入字典标签" />
          </el-form-item>
          <el-form-item label="字典键值"
                        prop="dictValue">
            <el-input v-model="formData.dictValue"
                      type="textarea"
                      :rows="5"
                      placeholder="请输入字典键值" />
          </el-form-item>
          <el-form-item label="字典排序"
                        prop="dictSort">
            <el-input-number v-model="formData.dictSort"
                             :min="0"
                             :precision="0"
                             style="width: 100%"
                             placeholder="请输入显示排序" />
          </el-form-item>
          <el-form-item label="样式回填"
                        prop="listClass">
            <el-select v-model="formData.listClass"
                       placeholder="请选择样式属性"
                       style="width: 100%">
              <el-option label="主要(primary)"
                         value="primary" />
              <el-option label="成功(success)"
                         value="success" />
              <el-option label="信息(info)"
                         value="info" />
              <el-option label="警告(warning)"
                         value="warning" />
              <el-option label="危险(danger)"
                         value="danger" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注"
                        prop="remark">
            <el-input v-model="formData.remark"
                      placeholder="请输入备注内容" />
          </el-form-item>
          <el-form-item label="状态"
                        prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="0">正常</el-radio>
              <el-radio :label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </template>
    </sys-dialog>

  </div>
</template>

<style scoped lang="scss">
.container {
  padding: 20px 20px 0px;

  /*顶部搜索卡片*/
  .search-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 15px 20px;
    }

    /*搜索表单*/
    .search-wrapper {
      .demo-form-inline {
        .el-form-item {
          margin-bottom: 0;
          margin-right: 15px;

          &:last-child {
            margin-right: 0;
          }

          .separator {
            margin: 0 5px;
            color: #909399;
          }
        }

        .el-input,
        .el-select {
          width: 220px;
        }
      }
    }
  }

  /*数据表格卡片*/
  .list-card {
    :deep(.el-card__body) {
      padding: 15px 20px 5px;
    }

    /*表格样式*/
    :deep(.el-table) {
      // 可扩展表格插槽列自定义样式
    }
  }

  // 分页器
  .pagination {
    margin-top: 15px;
  }
}
</style>
